import React, { Component } from 'react'
import './Chat.css'
import { connect } from 'react-redux'
import { NavBar } from 'antd-mobile'
import SendMsg from '../../components/SendMsg/SendMsg'
import { getUserChatMesgAxios } from '../../api/api'
import { sendMsgIo } from '../../redux/user/actions'

class Chat extends Component {
   state = {
      targetInfo: {},
      chatList: []
   }
   chatListRef = React.createRef() // 聊天信息列表容器
   componentDidMount() {
      // 初始化目标用户信息
      this.setState({ targetInfo: this.props.location.state.targetInfo })
      // 获取当前用户的聊天信息
      getUserChatMesgAxios().then(res => {
         res.data.chatMsgs.length > 0 && this.setState({ chatList: res.data.chatMsgs })
      })
   }
   componentDidUpdate() {
      // 让聊天列表容器滚动到最底部
      this.chatBoxScrollToBottm()
   }
   /* 返回按钮操作 */
   back = () => {
      this.props.history.goBack()
   }
   /* 发送消息执行的操作 */
   emitMessage = (content, callback) => {
      const from = this.props.myInfo._id
      console.log(this.props.myInfo)
      const to = this.state.targetInfo._id
      console.log(this.state.targetInfo)
      // 通过socket发送消息
      this.props.sendMsgIo({ from, to, content })
      const newChat = {
         chat_id: `${from}_${to}`,
         content: content,
         from: from,
         to: to,
         _id: this.props.myInfo._id
      }
      this.setState({ chatList: [...this.state.chatList, newChat] })
      callback && callback()
   }
   /* 消息列表容器滚动到最底部 */
   chatBoxScrollToBottm = () => {
      let current = this.chatListRef.current
      current.scrollTop = current.scrollHeight
   }
   render() {
      const { username, header: youHeader, type } = this.state.targetInfo
      const { header: myHeader, _id: myId } = this.props.myInfo
      const { chatList } = this.state
      return (
         < div className='user-detail' >
            <NavBar back='返回' onBack={this.back}>{username}<span style={{fontSize:12}}>-{type==='dashen'?'大神':'老板'}</span></NavBar>
            {/* 对话框列表 */}
            <div className='chat-list-box' ref={this.chatListRef}>{
               chatList.length > 0 && chatList.map((item, index) => {
                  return (
                     <div className="dialogue-list" key={index}>{
                        item.from === myId ?
                           <div className="item-my">
                              <p>{item.content}</p>
                              <img src={myHeader} alt="" />
                           </div> :
                           <div className="item-you">
                              <img src={youHeader} alt="" />
                              <p>{item.content}</p>
                           </div>
                     }</div>
                  )
               })
            }</div>
            <SendMsg submit={this.emitMessage} scrollEnd={this.chatBoxScrollToBottm}/>
         </ div >
      )
   }
}

export default connect(
   state => ({ myInfo: state.user }),
   { sendMsgIo }
)(Chat)